package com.simba.filter;

import com.simba.system.entity.Menu;
import com.simba.system.entity.Role;
import com.simba.system.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据请求的url分析请求所需要的角色
 */
@Slf4j
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menus = menuService.getMenusWithRoleByUrl(requestUrl);
        log.info("查询记录:"+menus.size()+"条，进入CustomFilter，请求的url："+requestUrl);
        for (Menu menu : menus) {
            //判断请求的url与菜单角色是否匹配
            log.info("进入循环中，判断请求的url与菜单角色是否匹配，开始匹配：" + menu.getUrl());
            if(antPathMatcher.match(menu.getUrl(),requestUrl)){
                log.info(menu.getUrl()+"+匹配上了requestUrl："+requestUrl);
                String[] str = menu.getRoles().stream().map(Role::getRoleKey).toArray(String[]::new);
                log.info(str.length+"==添加权限列表："+str[0]);
                return SecurityConfig.createList(str);
            }
        }
        log.info("权限控制表中没有找到url：" + requestUrl + "匹配的角色,授权该url为ROLE_LOGIN登录即可访问！");
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
